<template>
  <div>
    <h3>训练中心管理</h3>
    <div class="container">
      <vxe-toolbar>
        <template #buttons>
          <el-button type="success" icon="el-icon-plus" size="mini" @click="insertEvent">新增</el-button>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="xTable" max-height="800" keep-source border stripe highlight-hover-row
        highlight-current-row :loading="loading" :data="centerConfigTableData" @sort-change="sortChange" class="mytable-style"
        :cell-class-name="cellClassName" :edit-config="{trigger: 'click', mode: 'cell'}"
        @edit-actived="editActivedMethod" @edit-closed="editClosedMethod">
        <vxe-table-column field="name" title="训练分支机构名称" :filters="[{data: ''}]"
          :filter-method="customStringFilterMethod" sortable
          :edit-render="{name: 'input',autoselect: true, attrs: {type: 'text', placeholder: '请输入训练分支机构名称'}}">
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
        </vxe-table-column>
        <vxe-table-column field="sportNames" title="运动项目" :filters="[{data: ''}]"
          :filter-method="customStringFilterMethod" sortable>
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
          <template #default="{ row }">
            <div style="display: flex;justify-content: space-between;position: relative;">
              <span>{{row.sportNames}}</span>
              <vxe-button style="position: absolute;right: 0;top: 25%;" @click="sportEdit(row)" type="text" status="success"><i
                  class="el-icon-edit"></i>
              </vxe-button>
            </div>
          </template>
        </vxe-table-column>
        <vxe-table-column field="userNames" title="教职员" :filters="[{data: ''}]"
          :filter-method="customStringFilterMethod" sortable>
          <template #filter="{ column }">
            <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data"
              @change="filterEvent(option)" placeholder="请输入" clearable></vxe-input>
          </template>
          <template #default="{ row }">
            <div style="display: flex;justify-content: space-between;position: relative;">
              <span>{{row.userNames}}</span>
              <vxe-button style="position: absolute;right: 0;top: 25%;" @click="userEdit(row)" type="text" status="success"><i
                  class="el-icon-edit"></i>
              </vxe-button>
            </div>
          </template>
        </vxe-table-column>
        <vxe-table-column field="" title="操作" width="80" sortable>
          <template #default="{ row }">
            <vxe-button @click="centerDelete(row)" type="text" status="success"><i class="el-icon-delete"></i>
            </vxe-button>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize"
        :total="page.totalResult" :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
        @page-change="handlePageChange">
      </vxe-pager>
      <vxe-modal v-model="showEditSport" title="运动项目分配" width="500" min-width="600" height="80%" resize
        destroy-on-close>
        <template #default="params">
          <div style="display: flex;justify-content: space-between">
            <div style="margin-right: 20px;">
              <h5>所有运动大项</h5>
              <vxe-table resizable show-overflow border stripe size="mini" min-width="200" max-height="650" ref="allSportTable"
                highlight-hover-row highlight-current-row :data="allSport">
                <vxe-table-column field="name" title="权限" width="100"></vxe-table-column>
                <vxe-table-column field="" title="" width="60" height="36" sortable>
                  <template #default="{ row,rowIndex }">
                    <vxe-button @click="plusSport(row,rowIndex)" type="text"><i class="vxe-icon--plus"
                        style="font-weight: bold"></i></vxe-button>
                  </template>
                </vxe-table-column>
              </vxe-table>
            </div>
            <div>
              <h5>{{currentName}}拥有的运动大项</h5>
              <vxe-table resizable show-overflow border stripe size="mini" min-width="200" max-height="650" highlight-hover-row highlight-current-row ref="currentSportTable"
                :data="currentSport">
                <vxe-table-column field="name" title="权限" width="100"></vxe-table-column>
                <vxe-table-column field="" title="" width="60" height="36" sortable>
                  <template #default="{ row }">
                    <vxe-button @click="minusSport(row)" type="text"><i class="vxe-icon--minus"
                        style="font-weight: bold"></i></vxe-button>
                  </template>
                </vxe-table-column>
              </vxe-table>
            </div>
          </div>
        </template>
      </vxe-modal>
      <vxe-modal v-model="showEditUser" title="人员分配" width="600" min-width="600" height="80%" resize destroy-on-close>
        <template #default="params">
          <div style="display: flex;justify-content: space-between">
            <div style="margin-right: 20px;">
              <h5>所有教职员</h5>
              <vxe-table resizable show-overflow border stripe size="mini" min-width="200" max-height="650" ref="allRoleTable"
                highlight-hover-row highlight-current-row :data="allUser2Emp">
                <vxe-table-column field="userName" title="教职员" width="100" sortable></vxe-table-column>
                <vxe-table-column field="sportNames" title="运动项目" width="100" sortable></vxe-table-column>
                <vxe-table-column field="" title="" width="60" height="36" sortable>
                  <template #default="{ row,rowIndex  }">
                    <vxe-button @click="plusUser(row,rowIndex )" type="text"><i class="vxe-icon--plus"
                        style="font-weight: bold"></i></vxe-button>
                  </template>
                </vxe-table-column>
              </vxe-table>
            </div>
            <div>
              <h5>{{currentName}}负责人</h5>
              <vxe-table resizable show-overflow border stripe size="mini" min-width="200"  max-height="650" highlight-hover-row
              highlight-current-row ref="currentRoleTable"
                :data="currentUser">
                <vxe-table-column field="empName" title="教职员" width="100" sortable></vxe-table-column>
                <vxe-table-column field="sportNames" title="运动项目" width="100" sortable></vxe-table-column>
                <vxe-table-column field="" title="" width="60" height="36" sortable>
                  <template #default="{ row,rowIndex }">
                    <vxe-button @click="minusUser(row,rowIndex)" type="text"><i class="vxe-icon--minus"
                        style="font-weight: bold"></i></vxe-button>
                  </template>
                </vxe-table-column>
              </vxe-table>
            </div>
          </div>
        </template>
      </vxe-modal>
    </div>
  </div>
</template>

<script>
  import {
    config,
    centerUserInsert,
    centerUserDelete,
    centerSportInsert,
    centerSportDelete,
    sport_by_org,
    centerSportSelect,
    centerInsert,
    centerUpdate,
    centerDelete
  } from '@/api/organization.js'
  import {
    userId2EmpName,
    centerUserSelect
  } from '@/api/person.js'
  import {
    get_sport
  } from '@/api/dict.js'
  export default {
    name: 'centerConfig',
    data() {
      return {
        dict_sport: {},
        allUser2Emp: [],
        currentUser: [],
        allSport: [],
        currentSport: [],
        showEditSport: false,
        showEditUser: false,
        centerConfigTableData: [],
        centerConfigData: [],
        dict_sys_user: {},
        loading: false,
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        currentName: null,
        currentCenterId: null,
        currentRow: {},
      }
    },
    created() {
      this.initDict().then(() => {
        this.getCenterConfig()
      })
    },
    methods: {
      cellClassName({
        row,
        rowIndex,
        column,
        columnIndex
      }) {
        if (column.property === 'userNames'||column.property === 'sportNames') {
            return 'col-padding'
        }
      },
      plusUser(row,rowIndex ) {
        centerUserInsert({
          centerId: this.currentCenterId,
          userId: row.userId
        }).then(result => {
          if (result.code == 200) {
            // this.userEdit()
            this.$refs.allRoleTable.remove(this.allUser2Emp[rowIndex])
            this.currentUser.push(row)
            let currentRowUserArr = []
            let currentRowUserNameArr = []
            if(this.currentRow.userIds){
              currentRowUserArr = this.currentRow.userIds.split(',')
            }
            currentRowUserArr.push(row.userId)
            this.currentRow.userIds = currentRowUserArr.join(',')
            if(this.currentRow.userNames){
              currentRowUserNameArr = this.currentRow.userNames.split(',')
            }
            currentRowUserNameArr.push(row.userName)
            this.currentRow.userNames = currentRowUserNameArr.join(',')
            setTimeout(()=>{
              this.currentUser.forEach((item,index)=>{
                if(row.userId==item.userId){
                  this.$refs.currentRoleTable.setCurrentRow(this.currentUser[index])
                }
              })
            },100)


            // this.allUser2Emp.forEach((item,index)=>{
            //   if(row.userId==item.userId){
            //     this.allUser2Emp.splice(index,1)
            //   }
            // })
            // this.currentUser.unshift(row)

            // this.allUser2Emp.splice(this.allUser2Emp.indexOf(row), 1)
            // this.currentUser.push(row)
            // this.currentUser.sort((a, b) => {
            //   return a.userId - b.userId
            // })
            this.$message({
              showClose: true,
              message: '添加成功!',
              type: 'success'
            });
            // this.getCenterConfig()
          } else {
            this.$message({
              showClose: true,
              message: result.message,
              type: 'error'
            });
          }
        })
      },
      minusUser(row,rowIndex) {
        centerUserDelete({
          centerId: this.currentCenterId,
          userId: row.userId
        }).then(result => {
          if (result.code == 200) {
            this.userEdit()
            let currentRowUserArr = []
            let currentRowUserNameArr = []
            if(this.currentRow.userIds){
              currentRowUserArr = this.currentRow.userIds.split(',')
            }
            currentRowUserArr.splice(currentRowUserArr.indexOf(row.userId),1)
            this.currentRow.userIds = currentRowUserArr.join(',')
            if(this.currentRow.userNames){
              currentRowUserNameArr = this.currentRow.userNames.split(',')
            }
            currentRowUserNameArr.splice(currentRowUserNameArr.indexOf(row.empName),1)
            this.currentRow.userNames = currentRowUserNameArr.join(',')
            setTimeout(()=>{
              this.allUser2Emp.forEach((item,index)=>{
                if(row.userId==item.userId){
                  this.$refs.allRoleTable.setCurrentRow(this.allUser2Emp[index])
                }
              })
            },100)
            // this.currentUser.splice(this.currentUser.indexOf(row), 1)
            // this.allUser2Emp.push(row)
            // this.allUser2Emp.sort((a, b) => {
            //   return a.userId - b.userId
            // })
            this.$message({
              showClose: true,
              message: '删除成功！',
              type: 'success'
            });
            // this.getCenterConfig()
          } else {
            this.$message({
              showClose: true,
              message: result.message,
              type: 'error'
            });
          }
        })
      },
      plusSport(row,rowIndex) {
        centerSportInsert({
          centerId: this.currentCenterId,
          sportId: row.sportId
        }).then(result => {
          if (result.code == 200) {
            this.$refs.allSportTable.remove(this.allSport[rowIndex])
            this.currentSport.push(row)
            // this.sportEdit()
            let currentRowSportArr = []
            let currentRowSportNameArr = []
            if(this.currentRow.sportIds){
              currentRowSportArr = this.currentRow.sportIds.split(',')
            }
            currentRowSportArr.push(row.sportId)
            this.currentRow.sportIds = currentRowSportArr.join(',')
            if(this.currentRow.sportNames){
              currentRowSportNameArr = this.currentRow.sportNames.split(',')
            }
            currentRowSportNameArr.push(row.name)
            this.currentRow.sportNames = currentRowSportNameArr.join(',')
            setTimeout(()=>{
              this.currentSport.forEach((item,index)=>{
                if(row.sportId==item.sportId){
                  this.$refs.currentSportTable.setCurrentRow(this.currentSport[index])
                }
              })
            },100)
            this.$message({
              showClose: true,
              message: '添加成功！',
              type: 'success',
            })
            // this.getCenterConfig()
          } else {
            this.$message({
              showClose: true,
              message: result.message,
              type: 'error'
            });
          }
        })
      },
      minusSport(row) {
        centerSportDelete({
          centerId: row.centerId,
          sportId: row.sportId
        }).then(result => {
          if (result.code == 200) {
            // this.currentSport.splice(this.currentSport.indexOf(row), 1)
            // this.allSport.push(row)
            // this.allSport.sort((a, b) => {
            //   return a.sportId - b.sportId
            // })
            this.sportEdit()
            let currentRowSportArr = []
            let currentRowSportNameArr = []
            if(this.currentRow.sportIds){
              currentRowSportArr = this.currentRow.sportIds.split(',')
            }
            currentRowSportArr.splice(currentRowSportArr.indexOf(row.sportId),1)
            this.currentRow.sportIds = currentRowSportArr.join(',')
            if(this.currentRow.sportNames){
              currentRowSportNameArr = this.currentRow.sportNames.split(',')
            }
            currentRowSportNameArr.splice(currentRowSportNameArr.indexOf(row.name),1)
            this.currentRow.sportNames = currentRowSportNameArr.join(',')
            setTimeout(()=>{
              this.allSport.forEach((item,index)=>{
                if(row.sportId==item.sportId){
                  this.$refs.allSportTable.setCurrentRow(this.allSport[index])
                }
              })
            },100)
            this.$message({
              showClose: true,
              message: '删除成功！',
              type: 'success'
            });
            // this.getCenterConfig()
          } else {
            this.$message({
              showClose: true,
              message: result.message,
              type: 'error'
            });
          }
        })
      },
      sportEdit(row) {
        if(row){
          this.currentName = row.name
          this.currentCenterId = row.centerId
          this.currentRow = row
        }
        sport_by_org().then(result => {
          if (result.code == 200) {
            this.allSport = result.data
          }
        }).then(() => {
          centerSportSelect({
            centerId: this.currentCenterId
          }).then(result => {
            if (result.code == 200) {
              this.currentSport = result.data
              this.currentSport.forEach(item => {
                item.name = this.dict_sport[item.sportId]
              })
              this.currentSport.forEach(a => {
                this.allSport.forEach((b, i) => {
                  if (a.sportId == b.sportId) {
                    this.allSport.splice(i, 1)
                  }
                })
              })
              this.showEditSport = true
            }
          })
        })
      },
      userEdit(row) {
        if(row){
          this.currentName = row.name
          this.currentCenterId = row.centerId
          this.currentRow = row
        }
        userId2EmpName().then(result => {
          if (result.code == 200) {
            this.allUser2Emp = result.data
            this.allUser2Emp.forEach(item => {
              item.sportNames = this.dict_sport[item.sportId]
            })
          }
        }).then(() => {
          centerUserSelect({
            centerId: this.currentCenterId
          }).then(result => {
            if (result.code == 200) {
              this.currentUser = result.data
              this.currentUser.forEach(item => {
                item.empName = this.dict_sys_user[item.userId]
              })
              this.currentUser.forEach(a => {
                a.sportNames = this.dict_sport[a.sportId]
                this.allUser2Emp.forEach((b, i) => {
                  b.empName = this.dict_sys_user[b.userId]
                  if (a.userId == b.userId) {
                    this.allUser2Emp.splice(i, 1)
                  }
                })
              })
              this.showEditUser = true
            }
          })
        })
      },
      editActivedMethod({
        row
      }) {
        this.currentName = row.name
        const $table = this.$refs.xTable
        $table.setActiveRow(row)
      },
      editClosedMethod({
        row
      }) {
        if (!row.centerId && row.name) {
          centerInsert({
            name: row.name
          }).then(result => {
            if (result.code == 200) {
              row.centerId = result.data.centerId
              this.$message({
                showClose: true,
                message: '保存成功！',
                type: 'success'
              });
            } else {
              this.$message({
                showClose: true,
                message: result.message,
                type: 'error'
              });
            }
          })
        } else {
          const $table = this.$refs.xTable
          $table.clearActived().then(() => {
            if (row.name == this.currentName) {
              this.$message({
                showClose: true,
                message: '未检测到修改！',
                type: 'info'
              });
              this.findList()
              return
            }
            this.loading = true
            let data = {
              centerId: row.centerId,
              name: row.name
            }
            centerUpdate(data).then(result => {
              if (result.code == 200) {
                row.saveStatus = 1
                this.getCenterConfig()
                this.findList()
                this.loading = false
                this.$message({
                  showClose: true,
                  message: '保存成功！',
                  type: 'success'
                });
              } else {
                this.$message({
                  showClose: true,
                  message: result.message,
                  type: 'error'
                });
              }
            })
          })
        }

      },
      // 删除
      centerDelete(row) {
        this.$XModal.confirm('您确定要删除【' + row.name + '】该条数据?').then(type => {
          const $table = this.$refs.xTable
          if (type === 'confirm') {
            centerDelete({
              centerId: row.centerId
            }).then(result => {
              if (result.code == 200) {
                $table.remove(row)
                this.getCenterConfig()
                this.findList()
                this.$message({
                  showClose: true,
                  message: '删除成功！',
                  type: 'success'
                });
              }
            })

          }
        })
      },
      insertEvent() {
        const $table = this.$refs.xTable
        $table.insert().then(({
          row
        }) => {
          $table.setActiveCell(row, 'name')
        })
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      customStringFilterMethod({
        option,
        row,
        column
      }) {
        if (option.data) {
          return this.$XEUtils.toValueString(row[column.property]).toLowerCase().indexOf(option.data) > -1
        }
        return true
      },
      filterEvent(option) {
        const xTable = this.$refs.xTable
        // 设置为选中状态
        option.checked = true
        // 修改条件之后，需要手动调用 updateData 处理表格数据
        xTable.updateData()
      },
      initDict() {
        return new Promise((resolve, reject) => {
          get_sport().then(res => {
            this.dict_sport = res
          })
          userId2EmpName().then(result => {
            if (result.code == 200) {
              let dict = {}
              result.data.forEach(item => {
                if (item.userName) {
                  dict[item.userId] = item.userName;
                } else {
                  dict[item.userId] = item.empName;
                }
              })
              this.dict_sys_user = dict;
              resolve()
            }
          })
        })
      },
      getCenterConfig() {
        config().then(result => {
          if (result.code == 200) {
            result.data.forEach(item => {
              if (item.userIds) {
                let users = item.userIds.split(',')
                let userNames = []
                users.forEach(user => {
                  if (this.dict_sys_user[user]) userNames.push(this.dict_sys_user[user])
                })
                item.userNames = userNames.join(',')
              } else {
                item.userNames = ''
              }
              if (item.sportIds) {
                let sports = item.sportIds.split(',')
                let sportNames = []
                sports.forEach(sport => {
                  sportNames.push(this.dict_sport[sport])
                })
                item.sportNames = sportNames.join(',')
              } else {
                item.sportNames = ''
              }
            })
            this.centerConfigData = result.data
          }
        }).then(() => {
          this.findList()
        })
      },
      sortChange() {
        this.page.pageSize = this.centerConfigData.length
        this.findList()
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.page.totalResult = this.centerConfigData.length
          this.centerConfigTableData = this.centerConfigData.slice((this.page.currentPage - 1) * this.page.pageSize,
            this.page.currentPage * this.page.pageSize)
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    padding: 10px;
    background-color: #FFFFFF;
  }

  .my-green {
    color: #0da883;
  }

  vxe-button:hover {
    color: #5c998a;
  }

  .vxe-button.type--button.theme--my-purple,
  .vxe-button.type--button.theme--my-purple:hover {
    color: #fff;
  }

  .vxe-button.type--button.theme--my-purple {
    background-color: #0da883;
  }

  .vxe-button.type--button.theme--my-purple:active {
    background-color: #042f25;
  }

  .vxe-button.type--button.theme--my-default,
  .vxe-button.type--button.theme--my-default:hover {
    color: #575555;
  }

  .vxe-button.type--button.theme--my-default:active {
    background-color: #042f25;
    color: #fff;
  }
</style>
